import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const username = computed(() => userInfo.value.username || '用户')
  const avatar = computed(() => userInfo.value.avatar || '')

  async function login({email, password}) {
    console.log('login', email, password)
    return new Promise((resolve, reject) => {
      // 模拟API调用
      setTimeout(() => {
        console.log('login', email, password == '1')
        if (email == '1@163.com' && password == '1') {
          token.value = 'token123456'
          userInfo.value = { email }
          setToken(token.value)
          setUserInfo(userInfo.value)
          resolve(true)
        } else {
          reject(new Error('用户名或密码错误'))
        }
      }, 1000)
    })
  }

  // 修改密码
  async function changePassword(currentPassword, newPassword, code) {
    return new Promise((resolve, reject) => {
      // 模拟API调用
      setTimeout(() => {
        if (currentPassword === 'wrongpassword') {
          reject(new Error('当前密码不正确'))
          return
        }
        
        // 模拟成功修改密码
        ElMessage.success('密码修改成功')
        resolve(true)
      }, 1000)
    })
  }

  // 发送验证码
  async function sendSecurityCode() {
    return new Promise((resolve) => {
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('验证码已发送')
        resolve(true)
      }, 500)
    })
  }

  // 辅助函数
  function setToken(value) {
    token.value = value
    localStorage.setItem('token', value)
  }
  
  function setUserInfo(value) {
    userInfo.value = value
    localStorage.setItem('userInfo', JSON.stringify(value))
  }

  return {
    // 状态
    token,
    userInfo,
    
    // 计算属性
    isLoggedIn,
    username,
    avatar,
    
    // 动作
    changePassword,
    sendSecurityCode,
    setToken,
    setUserInfo,
    login
  }
})